package com.atguigu.bigdata.spark.core.rdd.operator.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

//mapwithpartionindex 指定特定分区进行处理
public class Spark03_RDD_Operator_Transform1_JAVA {
    public static void main(String[] args) {
        // TODO 准备环境
        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");
        JavaSparkContext sc = new JavaSparkContext(conf);
        List<Integer> seq = Arrays.asList(1,2,3,4,5,6);
        JavaRDD<Integer> rdd = sc.parallelize(seq,2);
        // v1 为分区数 v2为输入数据 迭代器
        JavaRDD<Integer> mapPartionRDD = rdd.mapPartitionsWithIndex(new Function2<Integer, Iterator<Integer>, Iterator<Integer>>() {
            @Override
            public Iterator<Integer> call(Integer v1, Iterator<Integer> v2) throws Exception {
                List<Integer> temp = new ArrayList<Integer>();
                if(v1 == 0) {
                    while (v2.hasNext()){
                        temp.add(v2.next());
                    }
                }
                return temp.iterator();
            }
        }, false);

        List<Integer> res = mapPartionRDD.collect();
        for(Integer val : res) {
            System.out.println(val);
        }
        sc.stop();
    }
}
